// 用户相关接口
const express=require('express')
const router=express.Router()
const pool=require('../utils/db')
const Response=require('../utils/Response')
// 查询所有用户
router.get('/userlist', async (req,res)=>{
    let {page,pagesize} = req.query
    try {
        let startIndex= (page - 1) * pagesize
        let size= parseInt(pagesize)
        let sql ="select user_id,user_phone,user_name from cyss_user limit ?,?"
        let result = await pool.querySync(sql,[startIndex,size])
        let sql2 = "select count(*) as count from cyss_user"
        let result2 = await pool.querySync(sql2,[startIndex,size])
        let total = result2[0].count
        // console.log('查询一结果：',result,);
        // console.log('查询二结果',result2);
        // console.log('result[0].count',total);
        res.send(Response.ok({page:parseInt(page),pagesize:size,total,result}))
    } catch (error) {
        res.send(Response.error(error))
    }
})

// id查询用户
router.post('/user/id',(req,res) => {
    let user_id = req.body.user_id  //接收的参数格式，
    // console.log(req.body)
    console.log(user_id)
    let sql = "select * from cyss_user where user_id=?"
    pool.query(sql,[user_id],(error,result) => {
        if (error) {
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok(result))
    })
})
//通过 用户名模糊查询用户
router.post('/user-name',(req,res)=>{
    let {uname} = req.body
    
    console.log(req.body);
    let sql="select user_id,user_phone,user_name from cyss_user where user_name like ?"
    pool.query(sql,[`%${uname}%`],(error,result)=>{
        if(error){
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok(result))
    })
})

//用户信息修改
router.post('/user-edit',(req,res) => {
    let {user_name,user_pwd,user_phone,user_id} = req.body
    console.log('userInfo:',req.body);
    let sql = "update cyss_user set user_name=?,user_pwd=?,user_phone=? where user_id=?"
    pool.query (sql,[user_name,user_pwd,user_phone,user_id],(error,result) => {
        // console.log(sql);
        if(error){
            res.send(Response.error(500,error))
            throw error
        }
        // console.log(result);
        res.send(Response.ok(result))
    })
})


// 删除用户
router.post('/user-del',(req,res)=>{
    let {id}=req.body
    
    let sql="delete from cyss_user where user_id=?"
    pool.query(sql,[id],(error,result)=>{
        if(error) {
            res.send(Response.error(500,error))
            throw error
        }
        res.send(Response.ok())
    })
})

// 导出 router 对象
module.exports=router 